package vip.aning.gitsync.config;

import javafx.concurrent.Task;

import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolManager {

    private static ThreadPoolManager instance;
    private final ThreadPoolExecutor threadPool;

    // 私有构造函数，初始化线程池
    private ThreadPoolManager() {
        // 自定义线程工厂，设置线程名
        ThreadFactory threadFactory = new ThreadFactory() {
            private int counter = 0;

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("GitThread-" + counter++);
                return thread;
            }
        };

        // 自定义拒绝策略
        RejectedExecutionHandler rejectedHandler = (r, executor) -> {
            System.err.println("任务被拒绝: " + r.toString());
        };

        // 初始化线程池
        threadPool = new ThreadPoolExecutor(
                1, // 核心线程数
                1, // 最大线程数
                60, // 空闲线程存活时间
                TimeUnit.SECONDS, // 时间单位
                new LinkedBlockingQueue<>(10), // 任务队列
                threadFactory, // 自定义线程工厂
                rejectedHandler // 自定义拒绝策略
        );
    }

    // 获取单例实例
    public static synchronized ThreadPoolManager getInstance() {
        if (instance == null) {
            instance = new ThreadPoolManager();
        }
        return instance;
    }

    // 提交任务到线程池
    public void execute(Runnable task) {
        threadPool.execute(task);
    }

    /**
     * 执行长时间任务
     *
     * @param task 要执行的任务
     * @return
     */
    public Future<?> execute(Task<?> task) {
        // 提交任务到线程池
        return threadPool.submit(task);
    }

    // 关闭线程池
    public void shutdown() {
        threadPool.shutdown();
    }

    // 获取线程池状态
    public String getStatus() {
        return String.format("Active Threads: %d, Task Count: %d, Completed Tasks: %d",
                threadPool.getActiveCount(),
                threadPool.getTaskCount(),
                threadPool.getCompletedTaskCount());
    }
}